<?php

namespace app\admin\service\crud;

use app\common\model\dict\DictData;
use app\common\model\dict\DictType;
use think\facade\Db;
use tmcore\base\BaseService;

/**
 * 数据表服务类
 */
class TableService extends BaseService
{
    /**
     * 获取所有的数据列表
     * @param $params
     * @return array
     */
    public static function getAllTableList($params) {
        $sql = "SHOW TABLE STATUS WHERE 1 = 1";
        if (!empty($params['name'])) {
            $sql .= " AND name LIKE '%" . $params['name'] . "%'";
        }
        if (!empty($params['comment'])) {
            $sql .= " AND comment LIKE '%" . $params['comment'] . "%'";
        }

        $list = Db::query(Db::raw($sql)->getValue());
        $pageData = self::getPageData();
        return page_array($list, $pageData['limit'], $pageData['page']);
    }

    /**
     * 获取模型列表
     * @return array
     */
    public static function getModelList() {

        $path = base_path() . 'common/model/';
        if(!is_dir($path)) return [];

        // 获取所有文件匹配的路径
        $moduleFiles = glob($path . '*');

        // 返回文件路径
        $resultFiles = [];

        foreach ($moduleFiles as $file) {
            $fileBaseName = basename($file, '.php');
            // 兼容多级文件夹
            if (is_dir($file)) {
                $file = glob($file . '/*');
                foreach ($file as $item) {
                    if (is_dir($item)) {
                        continue;
                    }
                    $resultFiles[] = sprintf(
                        "\app\common\model\%s\%s",
                        $fileBaseName,
                        basename($item, '.php')
                    );
                }
            } else {
                $resultFiles[] = sprintf(
                    "\app\common\model\%s",
                    basename($file, '.php')
                );
            }
        }

        return $resultFiles;
    }

    /**
     * 获取字典类型数据列表
     * @param string $limit
     * @return array
     */
    public static function getCrudDictDataList($limit = ''): array
    {
        $list = [];
        if($limit) {
            //分割限制条件
            $arr = explode(',', $limit);
            foreach ($arr as $key => $value) {
                if(strpos($value, '@') !== false) {
                    $id = explode('@', $value)[0];
                    $ext = explode('@', $value)[1];
                } else {
                    $id = $value;
                    $ext = $value;
                }
                $list[$ext] = DictData::where(['type_id' => $id, 'status' => 1])->field('name,value')->order(['id' => 'desc', 'sort' => 'desc'])->select();
            }
        }

        return $list;
    }

    /**
     * 获取字典类型列表
     * @return array
     */
    public static function getCrudTypeList(): array
    {
        $list = DictType::field('id,name,value,status')->order(['id' => 'desc', 'sort' => 'desc'])->select();
        if($list->isEmpty()) return [];
        return $list->toArray();
    }
}